/*
 * LibraryLocations.java
 *
 * Copyright(c) 2010
 * Michael Kroez
 * kroez@studiorutton.de
 *
 * All rights reserved.
 *
 * $Id$
 * 
 */

package de.studiorutton.access;

import java.io.File;
import java.io.IOException;

import de.studiorutton.access.FileAccessException.ErrorCode;

import android.os.Environment;

public class FileLocation {
	public static String externalStorage = null;

	public String baseURL = "";
	public String remoteURIPath = "";
	public String localPath = "";
	public String fileName = "";
	public String encodingSuffix = "";
	public String charset = "";

	public String createFileURI() {
		String uriPath = baseURL + "/" + remoteURIPath + "/" + fileName;
		if (!encodingSuffix.equals(""))
			return uriPath + "." + encodingSuffix;
		else
			return uriPath;
	}

	public String createFilePath() throws FileAccessException {
		String filePath = null;
		try {
			filePath = getExternalStorage() + File.separator + localPath
					+ File.separator + fileName;
		} catch (IOException e) {
			throw new FileAccessException(
					ErrorCode.ERROR_CANNOT_FIND_EXTERNAL_STORAGE);
		}
		return filePath;
	}
	
	public String createTmpFilePath() throws FileAccessException {
		String filePath = null;
		try {
			filePath = getExternalStorage() + File.separator + localPath
					+ File.separator + fileName + ".tmp";
		} catch (IOException e) {
			throw new FileAccessException(
					ErrorCode.ERROR_CANNOT_FIND_EXTERNAL_STORAGE);
		}
		return filePath;
	}

	public String createFileDir() throws FileAccessException {
		String fileDir = null;
		try {
			fileDir = getExternalStorage() + File.separator + localPath;
		} catch (IOException e) {
			throw new FileAccessException(
					ErrorCode.ERROR_CANNOT_FIND_EXTERNAL_STORAGE);
		}
		return fileDir;
	}

	public String getContentEncoding() {
		if (fileName == null)
			throw new IllegalArgumentException("filename == null");
		if (fileName.endsWith(".Z"))
			return "deflate";
		else if (fileName.endsWith(".gz"))
			return "gzip";
		else
			return "identity";
	}

	public String createFilePathWithoutSuffix() throws FileAccessException {
		String filePath = createFilePath();
		if (filePath == null) {
			throw new IllegalArgumentException("filePath == null");
		}
		int pos = filePath.lastIndexOf('.');
		if (pos > 0 && pos < fileName.length() - 1) {
			return filePath.substring(0, pos);
		}
		return filePath;
	}

	public static void setExternalStorage(String extStorage) {
		externalStorage = extStorage;
	}

	public static String getExternalStorage() throws IOException {
		if (externalStorage != null )
			return externalStorage;
		else
			return Environment.getExternalStorageDirectory().getCanonicalPath();
	}
}
